﻿using Esponce.Models;
using System;
using Windows.System;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;

namespace Esponce
{
	public sealed partial class MainPage : Page
	{
		public MainPage()
		{
			this.InitializeComponent();

			this.DataContext = new MainViewModel();
			App.ViewModel = ViewModel;
			App.View = this;
		}

		public MainViewModel ViewModel
		{
			get
			{
				return this.DataContext as MainViewModel;
			}
		}

		private async void generate()
		{
			//Check if content is set
			if (!string.IsNullOrEmpty(ViewModel.Content))
			{
				ViewModel.IsLoading = true;
				await ViewModel.GenerateAsync();
				ViewModel.IsLoading = false;
			}
		}

		private void Generate_Click(object sender, RoutedEventArgs e)
		{
			generate();
		}

		private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
		{
			switch (e.Key)
			{
				case VirtualKey.Enter:
					ViewModel.Content = ((TextBox)sender).Text;
					generate();
					break;
			}
		}

		private bool isFirstScan = true;
		private async void Scan_Click(object sender, RoutedEventArgs e)
		{
			if (this.isFirstScan)
			{
				var dialog = new MessageDialog("Find a QR Code image and capture the QR Code into frame. Application will then decode the image and display the content.", "How to scan");
				await dialog.ShowAsync();
				this.isFirstScan = false;
			}

			try
			{
				string content = await ViewModel.CapturePictureAsync();
				if (content != null)
				{
					var dialog = new MessageDialog(content, "QR Code");
					dialog.ShowAsync();
				}
			}
			catch (Exception ex)
			{
				var dialog = new MessageDialog(ex.Message, "Error");
				dialog.ShowAsync();
			}
		}

		private async void ImportFile_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				string content = await ViewModel.BrowserFileAsync();
				if (content != null)
				{
					var dialog = new MessageDialog(content, "QR Code");
					dialog.ShowAsync();
				}
			}
			catch (Exception ex)
			{
				var dialog = new MessageDialog(ex.Message, "Error");
				dialog.ShowAsync();
			}
		}
	}
}
